//
//  MapViewController.m
//  InnoBeacon
//
//  Created by INNO on 14-1-22.
//  Copyright (c) 2014年 com.inno-vision. All rights reserved.
//

#import "MapViewController.h"
#import "ALDefaults.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "ASIDownloadCache.h"
#import "ASIWebPageRequest.h"
#import "Matrix.h"
#import "DrawView.h"

#define kAreaSizeWidth 106
#define kAreaSizeHeight 60

#define kScare ((320*568)/(106 * 60))

static NSString * const kUUID = @"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0";
static NSArray * const arrayUrls = [NSArray arrayWithObjects:
                                    @"http://183.62.35.107:4096/ibeacons/Open/PushDataByPicture.aspx?id=1",
                                    @"http://183.62.35.107:4096/ibeacons/Open/PushDataByPicture.aspx?id=2",
                                    @"http://183.62.35.107:4096/ibeacons/Open/PushDataByPicture.aspx?id=3",
                                    @"http://183.62.35.107:4096/ibeacons/Open/PushDataByPicture.aspx?id=4",
                                    @"http://183.62.35.107:4096/ibeacons/Open/PushDataByPicture.aspx?id=5",
                                    nil];
static struct beaconPoint const beaconPoints[3] = {{0,0,0},{0,568,0},{568,320,0}};



@interface MapViewController ()
{
    _Matrix pi;
    float distance[3];
    float point[2];
    
    NSMutableArray        *_rangedRegions;
    CLLocationManager     *_locationManger;
    NSMutableDictionary   *_distances;
    NSMutableDictionary   *_beacons;
    UIView                *thirdView;
    CLBeacon               *earlybeacon;
}

@property (nonatomic,strong) NSArray    *detectedBeacons;
@property (strong,nonatomic)  DrawView *drawView;

- (void)uploadFailed:(ASIHTTPRequest *)theRequest;
- (void)uploadFinished:(ASIHTTPRequest *)theRequest;

- (void)webPageFetchFailed:(ASIHTTPRequest *)theRequest;
- (void)webPageFetchSucceeded:(ASIHTTPRequest *)theRequest;

@end

@implementation MapViewController
@synthesize webRequest;
@synthesize upLoadRequest;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    UIImage* image = [UIImage imageNamed:@"导航图.png"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];
    
    
    //这里开始初始化
    _drawView = [[DrawView alloc] initWithFrame:self.view.bounds];
    _drawView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_drawView];
    
    webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
	[webView setDelegate:self];
    
    _distances = [[NSMutableDictionary alloc] init];
    _locationManger = [[CLLocationManager alloc] init];
    _locationManger.delegate = self;
    
    //设置位置精度
    _locationManger.desiredAccuracy = kCLLocationAccuracyBest;
    _rangedRegions = [NSMutableArray array];
    [[ALDefaults sharedDefaults].supportedProximityUUIDs enumerateObjectsUsingBlock:^(id uuidobj,NSUInteger uuidIndex, BOOL *uuidStop){
        NSUUID *uuid = (NSUUID *)uuidobj;
        CLBeaconRegion  *region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:[uuid UUIDString]];
        [_rangedRegions addObject:region];
        
    }];
    
    matrix_set(&pi, 3, 2);
    matrix_init(&pi);
    _calculateTimer = [NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(calculateTimeCallback:) userInfo:nil repeats:YES];
    
    _sendDataTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(sendDataToServerTimer:) userInfo:nil repeats:YES];
    
}

-(void)viewDidDisappear:(BOOL)animated
{
    if (_calculateTimer != nil) {
        [_calculateTimer invalidate];
        _calculateTimer = nil;
    }
    matrix_free(&pi);
    [_rangedRegions enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop){
        CLBeaconRegion  *region = obj;
        [_locationManger stopRangingBeaconsInRegion:region];
    }];
    [_locationManger stopUpdatingLocation];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [_rangedRegions enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop){
        CLBeaconRegion *region = obj;
        [_locationManger startRangingBeaconsInRegion:region];
    }];
    [_locationManger startUpdatingLocation];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSUInteger) supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

//清楚划过的线
-(void)clearPoint{
    [_drawView clear];
}


-(void)sendDataToServerTimer:(NSTimer *)timer
{
  if(earlybeacon){
      
    [upLoadRequest cancel];
    [self setUpLoadRequest:[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://183.62.35.107:4096/ibeacons/Open/DataByPost.aspx?auth=4ac9fb3a95b91bb2d22bb15e"]]];
    [upLoadRequest setPostValue:@"13579213456" forKey:@"phoneid"];
    [upLoadRequest setPostValue:[NSString stringWithFormat:@"%d",[earlybeacon.minor intValue]] forKey:@"ibeaconid"];
    [upLoadRequest setPostValue:@"1" forKey:@"status"];
    [upLoadRequest setTimeOutSeconds:20];
    
    #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
	[upLoadRequest setShouldContinueWhenAppEntersBackground:YES];
    #endif
    
    [upLoadRequest setDelegate:self];
	[upLoadRequest setDidFailSelector:@selector(uploadFailed:)];
	[upLoadRequest setDidFinishSelector:@selector(uploadFinished:)];
    
    [upLoadRequest startAsynchronous];

  }
        
}
-(void)calculateTimeCallback:(NSTimer *)timer
{
    //[self.view drawRect:[UIScreen mainScreen].applicationFrame];
//#define _DEBUG
#ifdef _DEBUG
    static float pointx = 20;
    static float pointy = 35;
    pointx += 10;
    pointy += 25;
    point[0] = pointx ;
    point[1] = pointy ;
    CGPoint aPoint = CGPointMake(point[0] , point[1]);
    [_drawView moveBegan:aPoint];
    
#endif
    float h = 0;
    if ([_distances count] < 3) {
        
        return;
    }
    
    distance[0] = [[_distances objectForKey:[NSNumber numberWithInt:1]] floatValue] ;
    
    distance[1] = [[_distances objectForKey:[NSNumber numberWithInt:2]] floatValue];
    
    distance[2] = [[_distances objectForKey:[NSNumber numberWithInt:3]] floatValue] ;
    
    
    
    //获取坐标
    matrix_write(&pi, 0, 0, beaconPoints[0].x);
    matrix_write(&pi, 0, 1, beaconPoints[0].y);
    h = beaconPoints[0].z;
    distance[0] = sqrt(distance[0] * distance[0] - h * h);
    
    matrix_write(&pi, 1, 0, beaconPoints[1].x);
    matrix_write(&pi, 1, 1, beaconPoints[1].y);
    h = beaconPoints[1].z;
    distance[1] = sqrt(distance[1] * distance[1] - h * h);
    
    matrix_write(&pi, 2, 0, beaconPoints[2].x);
    matrix_write(&pi, 2, 1, beaconPoints[2].y);
    h = beaconPoints[2].z;
    distance[2] = sqrt(distance[2] * distance[2] - h * h);
    
    NSLog(@"dis1 = %f,dis2 = %f,dis3 = %f",distance[0],distance[1],distance[2]);
    
    if (locate(&pi, distance, point) > 0) {
        NSLog(@"Point[0] = %f,point[1] = %f",point[0],point[1]);
        if (point[0] > self.view.bounds.size.width) {
            point[0] = self.view.bounds.size.width;
        }
        if(point[1] > self.view.bounds.size.height)
            point[1] = self.view.bounds.size.height;
        
        
        //根据point坐标画出活动轨迹
        CGPoint aPoint = CGPointMake(point[0] , point[1]);
        [_drawView moveBegan:aPoint];
        
    }
    
}


#pragma Mark -Location

-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region
{
    //CoreLocation will call this delegate method at 1 Hz with updated range information
    //Beacons will be categorized and displayed by proximity
    
    /*NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];
    date = [formatter stringFromDate:[NSDate date]];
    NSString* timeNow = [[NSString alloc] initWithFormat:@"%@", date];
    NSLog(@"%@", timeNow);*/
    
    [_beacons removeAllObjects];
    //[_distances removeAllObjects];
    
    for(int index = 0;index < [beacons count];index++){
        CLBeacon *curr = [beacons objectAtIndex:index];
        int mar = curr.major.intValue;
        if (1 == mar || 2 == mar || 3 == mar) {
            [_distances setObject:[NSNumber numberWithFloat:curr.accuracy] forKey:[NSNumber numberWithInt:mar]];
        }
    }
    
    NSArray *nearBeacons = [beacons filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"proximity = %d",CLProximityNear]];
    if([nearBeacons count])
    {
        //[_beacons setObject:nearBeacons forKey:[NSNumber numberWithInt:CLProximityNear]];
        CLBeacon *currBeacon = [nearBeacons lastObject];
        if (currBeacon.minor == earlybeacon.minor) {
            return ;
        }
        earlybeacon = [nearBeacons lastObject];
        [self fetchURL:[NSURL URLWithString:[arrayUrls objectAtIndex:[earlybeacon.minor intValue]]]];
    }
    
}

/*-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
 {
 if(![_rangedRegions isEqual:region])
 return;
 if([UIApplication sharedApplication].applicationState != UIApplicationStateBackground) return;
 
 if([self shouldIgnoreEvent])
 return;
 
 
 }*/

/*(-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
 {
 
 }

//当设备无法定位当前我位置时候调用此方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSString *errorType = (error.code == kCLErrorDenied)?@"Access Denied" : @"Unknown Error";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error getting Location" message:errorType delegate:nil cancelButtonTitle:@"oKay" otherButtonTitles:nil];
    
    [alert show];
}*/


- (void)exitThirdView:(id)sender
{
    //也加入动画效果
    [UIView beginAnimations:@"flipping view"
                    context:nil];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight
                           forView:self.view
                             cache:NO];
    [thirdView removeFromSuperview];
    [UIView commitAnimations];
    _locationManger = [[CLLocationManager alloc] init];
    _locationManger.delegate = self;
    [_rangedRegions enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop){
        CLBeaconRegion *region = obj;
        [_locationManger startRangingBeaconsInRegion:region];
    }];
    [_locationManger startUpdatingLocation];
    
}

-(void)createThridView
{
    //先创建view
    thirdView=[[UIView alloc]
               initWithFrame:self.view.bounds];
    thirdView.backgroundColor=[UIColor greenColor];
    
    //为view增加控件
    UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame=CGRectMake(100, 400, 100, 100);
    [button setTitle:@"回首页"
            forState:UIControlStateNormal];
    [button addTarget:self
               action:@selector(exitThirdView:)
     forControlEvents:UIControlEventTouchUpInside];
    [thirdView addSubview:button];
    
    //为view增加label控件
    UILabel*  label = [[UILabel alloc] initWithFrame:CGRectMake(50, 250, 250, 100)];
    label.text = @"欢迎光临广州天诺研发中心";
    label.textColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
    //label.backgroundColor = [UIColor cyanColor];
    [thirdView addSubview:label];
    
    
    CGRect r = [ UIScreen mainScreen ].applicationFrame;
    UIImage* image = [UIImage imageNamed:@"test.png"];
    UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
    imageview.frame = CGRectMake(0, 50, r.size.width, 200);
    [thirdView addSubview:imageview];
    
    
    //将view显示出来
    //加入动画吧
    [UIView beginAnimations:@"flipping view"
                    context:nil];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
                           forView:self.view
                             cache:NO];
    [self.view addSubview:thirdView];
    [UIView commitAnimations];
    
    [self.view endEditing:YES];
    [_locationManger stopUpdatingLocation];
    _locationManger = nil;
}


#pragma Mark -

- (void)uploadFailed:(ASIHTTPRequest *)theRequest
{
	//[resultView setText:[NSString stringWithFormat:@"Request failed:\r\n%@",[[theRequest error] localizedDescription]]];
   // NSLog(@"Request failed:%@",[[theRequest error] localizedDescription]);
}

- (void)uploadFinished:(ASIHTTPRequest *)theRequest
{
	//[resultView setText:[NSString stringWithFormat:@"Finished uploading %llu bytes of data",[theRequest postLength]]];
    NSLog(@"Finished uploading %llu byptes of data",[theRequest postLength]);
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
    // Clear out the old notification before scheduling a new one.
    if ([[[UIApplication sharedApplication] scheduledLocalNotifications] count] > 0)
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    // Create a new notification
    UILocalNotification *notification = [[UILocalNotification alloc]init];
    if (notification) {
		[notification setFireDate:[NSDate date]];
		[notification setTimeZone:[NSTimeZone defaultTimeZone]];
		[notification setRepeatInterval:0];
		[notification setSoundName:@"alarmsound.caf"];
		[notification setAlertBody:@"Boom!\r\n\r\nUpload is finished!"];
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
#endif
}

- (void)webPageFetchFailed:(ASIHTTPRequest *)theRequest
{
    NSLog(@"Something went wrong:%@",[theRequest error]);
}
- (void)webPageFetchSucceeded:(ASIHTTPRequest *)theRequest
{
    NSURL *baseURL;
    baseURL = [theRequest url];

	if ([theRequest downloadDestinationPath]) {
		NSString *response = [NSString stringWithContentsOfFile:[theRequest downloadDestinationPath] encoding:[theRequest responseEncoding] error:nil];
		[webView loadHTMLString:response baseURL:baseURL];
	} else {
		[webView loadHTMLString:[theRequest responseString] baseURL:baseURL];
	}
    
    //为view增加控件
    UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame=CGRectMake(100, 480, 100, 100);
    [button setTitle:@"回首页"
            forState:UIControlStateNormal];
    [button addTarget:self
               action:@selector(exitWebView:)
     forControlEvents:UIControlEventTouchUpInside];
    [webView addSubview:button];

    
    //[self.view addSubview:webView];
    self.view = webView;
    [UIView commitAnimations];
    
    [self.view endEditing:YES];

}

-(void)exitWebView:(id)sender
{
    //也加入动画效果
    [UIView beginAnimations:@"flipping view"
                    context:nil];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
                           forView:self.view
                             cache:NO];
    [webView removeFromSuperview];
    [UIView commitAnimations];
    earlybeacon = nil;
}

-(void) fetchURL:(NSURL *)url
{
    [webRequest setDelegate:nil];
    [webRequest cancel];
    
    [self setWebRequest:[ASIWebPageRequest requestWithURL:url]];
    [webRequest setDidFailSelector:@selector(webPageFetchFailed:)];
    [webRequest setDidFinishSelector:@selector(webPageFetchSucceeded:)];
    [webRequest setDelegate:self];
    [webRequest setDownloadProgressDelegate:self];
    [webRequest setUrlReplacementMode:ASIReplaceExternalResourcesWithData];
    
    //Set downloadDestinationPath for all ASIWebPageRequests
    [webRequest setDownloadCache:[ASIDownloadCache sharedCache]];
    [webRequest setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
    
    [webRequest setDownloadDestinationPath:[[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:webRequest]];
    
    [[ASIDownloadCache sharedCache] setShouldRespectCacheControlHeaders:NO];
    [webRequest startAsynchronous];
    
}

#pragma Mark-  webview

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        
        [self fetchURL:[request URL]];
        return  NO;
    }
    
    return YES;
}


























@end
